<?php

namespace App\Http\Controllers;

use App\Events\PostsSaved;
use App\Models\CostaNews;
use App\Jobs\Queue;
use App\Tools\LinkedList;
use App\Tools\ListNode;
use App\Tools\Solution;
use App\Tools\VerifyWalletAddress;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

use Overtrue\LaravelSendCloud\SendCloud;
use Symfony\Component\VarDumper\VarDumper;

class IndexController extends Controller
{

    public function __construct()
    {
        $solution = new Solution();
        $list=[2,4,3];
        $list2=[5,6,4];
        //$data = $solution->addTwoNumbers($list, $list2);
        $list = new ListNode(2);
        $list->next = new ListNode(4);
        $list->next->next = new ListNode(3);

        $list2 = new ListNode(5);
        $list2->next = new ListNode(6);
        $list2->next->next = new ListNode(4);


        $model = new Solution();
        $data =$model->addTwoNumbers($list, $list2);
//        $list->display();
//        echo "--------";
//        $list2->display();
dd($data);
        exit;
    }
    public function twoSumV3($nums, $target)
    {
        $data = [];
        foreach($nums as $i => $v) {
            $poor = $target - $v;
            $data[$poor] = $i;
        }
        foreach($nums as $i => $v) {

            if( isset($data[$v]) &&  $data[$v] != $i ) {
                return [$i, $data[$v]];
            }

        }
        return [];
    }
    function twoSumV2($nums, $target)
    {
        $temp_arr = [];
        foreach($nums as $index => $val) {
            $p_num = $target - $val;
            if(isset($temp_arr[$p_num])) {
                return [$temp_arr[$p_num], $index];
            }

            $temp_arr[$val] = $index;
        }

        return false;
    }

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer[]
     */
    function twoSum($nums, $target) {

        $return  = [];
        $numTmp = $nums;
        foreach ($nums as $k=>$v) {
            $break = false;
            unset($numTmp[$k]);
            foreach ($numTmp as $key=>&$value) {
                if ($v+$value == $target) {
                    $return= [$k, $key];
                    $break = true;
                    break;
                }
            }
            if ($break)break;

        }
        return $return;
    }



    public function reverse($num)
    {
        $pre = '';
        if ($num<0) {
            $pre = '-';
            $num = abs($num);
        }
        $numArr = str_split($num);
        $reverse  = array_reverse($numArr);
        $num = join('', $reverse);
        $abs = abs($num);
        if ($abs > 2147483647 || $abs<-2147483648) {
            return 0;
        }
        return $pre.$abs;
    }

    public function reverseV2($num)
    {
        $pre = '';
        if ($num<0) {
            $pre = '-';
            $num = abs($num);
        }
        $num = strrev($num);
        $abs = abs($num);
        if ($abs > 2147483647 || $abs<-2147483648) {
            return 0;
        }
        return $pre.$abs;
    }

    public function reverseV3($x)
    {

        if($x == 0)
            return 0;

        else if($x > 0)
        {
            $reverseNum = 0;
            $_2pow31 = pow(2,31);

            while($x > 0)
            {
                if ((($_2pow31 - 1 - $x % 10) / 10) < $reverseNum){
                    return 0;
                } else{
                    $reverseNum = $reverseNum * 10 + $x % 10;
                }
                $x = $x / 10;
            }
            return $reverseNum;
        }

        else if($x < 0)
        {
            $reverseNum = 0;
            $N_2pow31 = -1 * pow(2,31);
            while($x < 0)
            {
                if(($N_2pow31 - $x % 10) / 10 > $reverseNum)
                    return 0;
                else
                    $reverseNum = $reverseNum * 10 + $x % 10;
                $x = $x / 10;
            }
            return $reverseNum;
        }
        return 0;
    }

    public function reverseV4($x)
    {
        $pre = '';
        if ($x<0) {
            $pre = '-';
            $x = abs($x);
        }
        $reverseNum = 0;

        while($x >= 1)
        {
            $reverseNum = $reverseNum * 10 + $x % 10;

            $x = $x / 10;
        }
        if ($reverseNum > 2147483647 || $reverseNum<-2147483648) {
            return 0;
        }
        return $pre.$reverseNum;
    }

    /**
     * @param Integer $x
     * @return Integer
     */
    public function reverseV5($x)
    {
        $nInterim = 1;
        if ($x < 0) $nInterim = -1;

        $x *= $nInterim;
        // 反转数字
        $x = strrev($x);
        $x = $x * $nInterim;
        if ($x >= pow(2, 31) - 1) return 0;
        if ($x <= pow(2, 31) * -1 ) return 0;

        return $x;
    }

    public function index(Request $request)
    {
        $origin =[];
        $current=[];
        for($i=1;$i<10000;$i++) {
            $origin[] =  ['id' => $i, 'title' => 'title'.$i, 'content' => 'name'.$i];
        }
        for($i=9998;$i<10500;$i++) {
            $current[] = 'title'.$i;
        }
        $t1 = microtime(true);


        /*//把title取出来做为键
        $origin_new = array_combine(array_column($origin, 'title'), $origin);
        //把值作为键
        $current_new = array_flip($current);

        //新的源 （用键来做差集比较得出新的源）
        $new_origin = array_diff_key($origin_new, $current_new);
        //新的当前
        $new_current = array_diff_key($origin_new, $new_origin);*/

        $data = $this->splitArr($origin, $current);

        $t2 = microtime(true);
        dd($t2 - $t1, $data);


        return view('welcome');
    }

    /**
     * 分割数组
     * @param $origin 原数组
     * @param $split 分割数组 （源数组中的某个键的值）
     * @return array ['split'=>被分割出来的数组, 'remainders'=>剩余的数据];
     */
    public function splitArr($origin, $split)
    {
        //把title取出来做为键
        $origin_new = array_combine(array_column($origin, 'title'), $origin);
        //把值作为键
        $split_new = array_flip($split);

        //剩余的源数据 （用键来做差集比较得剩余的源数据）
        $remainders = array_diff_key($origin_new, $split_new);
        //被分割出来的数据
        $new_split = array_diff_key($origin_new, $remainders);

        return ['split'=>$new_split, 'remainders'=>$remainders];
    }

    /**
     * 根据key删除数组中指定元素
     * @param  array $arr 数组
     * @param  string/int  $key  键（key）
     */
    function array_remove_by_key($arr, $key)
    {
        if (!array_key_exists($key, $arr)) {
            return $arr;
        }
        $keys = array_keys($arr);
        $index = array_search($key, $keys);
        if ($index !== FALSE) {
            array_splice($arr, $index, 1);
        }
        return $arr;

    }


    public function arrayTest()
    {
        $array = ['name' => 'Joe', 'languages' => ['PHP', 'Ruby']];

        $flattened = array_flatten($array);


        dd($flattened);

    }


    public function event()
    {
        event(new  PostsSaved(['content' => '哈哈哈，您关注的博主发不了一条新内容']));
        return response()->json(['code' => 0, 'msg' => "success"]);
    }

    public function mq()
    {
        $data = CostaNews::get();
        foreach ($data as $item) {
            $this->dispatch(new Queue($item));
        }
        return response()->json(['code' => 0, 'msg' => "success"]);
    }

    public function base58()
    {
        $walletAddress = 'bcbD5WCcBsYd1RPPiUWbMRaoLbsHBPHhzYdz';
        $prefix = 'bcb';
        $check = VerifyWalletAddress::verify($walletAddress, $prefix);

        $testAlletAddress = 'bcbtestPoEkHihpa28tHmD83vWJyA6Jpthz7eTaK';
        $testPrefix = 'bcbtest';
        $checkTest = VerifyWalletAddress::verify($testAlletAddress, $testPrefix);
        dd($check, $checkTest);
    }


    public function strtoascii($str)
    {
        $str = mb_convert_encoding($str, 'GB2312');
        $change_after = '';
        for ($i = 0; $i < strlen($str); $i++) {
            $temp_str = dechex(ord($str[$i]));
            $change_after .= $temp_str[1] . $temp_str[0];
        }
        return strtoupper($change_after);
    }

    public function asciitostr($sacii)
    {
        $asc_arr = str_split(strtolower($sacii), 2);
        $str = '';
        for ($i = 0; $i < count($asc_arr); $i++) {
            $str .= chr(hexdec($asc_arr[$i][1] . $asc_arr[$i][0]));
        }
        return mb_convert_encoding($str, 'UTF-8', 'GB2312');
    }

    public function sendEmail()
    {
        $username = "独孤求败";
        $title = "欢迎使用laravel 邮件系统";
        $result = Mail::send('emails.welcome', ['username' => $username], function ($message) use ($title) {
            $message->subject($title);
            $message->from('blog@service.tjnccy.cn', '武林至尊联盟');
            $message->to('990921093@qq.com')->cc('tjnccy@qq.com');
        });
        \Log::channel('register')->info($username . '---' . $title);
        dd('发送成功');
    }

    public function rmSend()
    {
        $data = CostaNews::get();
        foreach ($data as $item) {
            $this->dispatch(new Queue($item));
        }
        return response()->json(['code' => 0, 'msg' => "success"]);
    }

    public function sendMq()
    {
        /**
         * 发送消息
         */

        $queueName = 'queue_name';
        $routeKey = 'queue_name';
        $message = 'Hello World!';
        // 建立TCP连接
        $connection = new \AMQPConnection([
                                              'host' => 'rabbitmq',
                                              'port' => '5672',
                                              'vhost' => '/',
                                              'login' => 'guest',
                                              'password' => 'guest'
                                          ]);
        $connection->connect() or die("Cannot connect to the broker!\n");

        $channel = new \AMQPChannel($connection);

        $queue = new \AMQPQueue($channel);
        $queue->setName($queueName);

        $exchange = new \AMQPExchange($channel);
        $data = ['id' => 1, 'name' => 'tang3'];
        $result = $exchange->publish(json_encode($data), $routeKey);
        // 断开连接
        $connection->disconnect();
        VarDumper::dump($result);
    }

    public function recMq()
    {
        $queueName = 'queue_name';
        // 建立TCP连接
        $connection = new \AMQPConnection([
                                              'host' => 'rabbitmq',
                                              'port' => '5672',
                                              'vhost' => '/',
                                              'login' => 'guest',
                                              'password' => 'guest'
                                          ]);
        $connection->connect() or die("Cannot connect to the broker!\n");

        $channel = new \AMQPChannel($connection);
        $channel->qos(0, 0);
        $queue = new \AMQPQueue($channel);
        $queue->setName($queueName);
        $queue->declareQueue();
        $result = $queue->get();

        if ($result) {
            $msg = $result->getBody();
            $envelopeID = $result->getDeliveryTag();
            //确定收到消息，刪除记录
            $queue->ack($envelopeID);
            var_dump($msg);
        }

    }

}
